var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var cookieParser = require("cookie-parser");
var template = require("art-template");
var DB = require("./libs/db.js");
var Customer = DB.Customer;
var Goods = DB.Goods;
app.use(express.static("wwwroot"));
app.use(bodyParser.urlencoded({extended:false}));
app.engine(".html",template.__express);
//res.render指定模板和数据，需要一个html字符串，并返回客户端，
//这个方法会在默认文件（views）中去寻找模板。
app.set("view engine","html");
//开发时候关闭缓存，生产时需要打开。
template.config("cache",false);
app.get("/",function(req,res)
{
	res.render("index");
});

//注册接口;
app.post("/register",function(req,res)
{
	var cus = new Customer(
	{
		name: req.body.username,
		cipher: req.body.psw,
		tel: Number(req.body.tel)
	});
	cus.save(function(err)
	{
		if(err)
		{
			res.send({state:1,msg:err});
		}else
		{
			res.send({state:0,msg:"注册成功"});
		}
	});
});
//登录接口
app.post("/login",function(req,res)
{
//	console.log(req.body);
	Customer.find({name:req.body.username},function(err,data)
	{
		if(data[0].cipher==req.body.psw)
		{
			//发送一个cookie到客户端，当做登录凭证;//并发送当前人的Id值到客户端
//			console.log(data[0]._id)
			res.cookie("username",req.body.username);
			res.cookie("userID",data[0]._id);
			res.send({state:0,msg:"登录成功"});
		}else
		{
			res.send({state:1,msg:"密码输入错误"});
		}
	});
});
//检测用户存在否接口
app.get("/usernameExist",function(req,res)
{
	Customer.find({name:req.query.username},function(err,data)
	{
		if(err)
		{
			res.send({state:1,msg:'查询错误'});
		}else
		{
			if(data.length<=0)
			{
				res.send({state:2,msg:"用户名不存在"});
			}else
			{
				res.send({state:0,msg:"用户存在"});
			}
		}
	});
});
//添加购物车接口，点击添加到购物车时候调用
app.get("/goods/add",function(req,res){
//	console.log(req.query);
	new Goods(req.query).save(function(err){
		if(err){
			res.send({state:1,msg:"添加失败"});
		}else{
			res.send({state:0,msg:"添加成功"});
		}
	});
});

//查看购物车
app.get("/goods/all",function(req,res){
//	res.send("查看所有商品");

//	console.log(req.query.id);

	Goods.find({userId:req.query.id},function(err,result){
//		
		console.log(result);
		res.render("myCar",{Goods:result});
	}).populate("Customer");
});

//删除购物车中的
app.get("/goods/delete",function(req,res){
//	console.log(req.query.currentId);
	Goods.find({_id:req.query.currentId},function(err,data)
	{
//		console.log(data);
		var theOneId = data[0].userId;
		if(err){return;}
		else
		{
//			console.log(theOneId);
			Goods.remove({_id:req.query.currentId},function(err)
			{
				if(err){
					console.log(err+"123");
				}else{
					res.redirect("/goods/all?id="+theOneId);
				}
			})
		}
	});
	
//	res.redirect("/tradeDetail.html");
	
})


app.listen(8100,function()
{
	console.log("服务器开启成功！");
});
